const https = require('https')
const http = require('http')


http.createServer((req, res) => {

  res.writeHead(200,{
    "Content-Type": "application/json;charset=utf-8",
    "access-control-allow-origin": "*"
  })
  console.log(111)
  // 作为中间层，去猫眼拿数据，然后返回给自己get
  if(req.url == '/a') {
    httpGet((data) => {
      res.end(data)
    })
  } 

    // 作为中间层，去猫眼拿数据，然后返回给自己post
  if(req.url == '/b') {
    httpPost((data) => {
      res.end(data)
    })
  }


}).listen(5556,() => {
  console.log('5556 server runing')
})


function httpGet (cb) {
  let data = ''
  const url = 'https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E4%B8%8A%E6%B5%B7&ci=10&channelId=4'
  https.get(url, (res) => {
    // 数据以流的形式接收
    res.on('data', (chunk) => {
      data += chunk
    })
    // 接收完出发end事件
    res.on('end', () => {
      console.log(data)
      cb(data)
    })
  })
}

function httpPost (cb) {
  let data = ''
  // const url = 'https://m.xiaomiyoupin.com/mtop/mf/resource/data/batchList'
  const options = {
    hostname: 'm.xiaomiyoupin.com',
    port: '443',
    path: '/mtop/market/search/placeHolder',
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
      "Cookie": "youpindistinct_id=18fd17b0308-0b899f87c6b775-29ed; mjclient=M; youpin_sessionid=18fd194ea9b-029f713860cfda-29ed",
      "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36 Edg/122.0.0.0"
    }
  }
  const req = https.request(options,(res) => {
    res.on('data',(chunk) => {
      data += chunk
    })

    res.on('end', () => {
      cb(data)
    })
  })
  // post 的 params参数
  req.write(JSON.stringify([
    {},
    {
        "baseParam": {
            "ypClient": 1
        }
    }
]))
  req.end()

}